package cn.stylefeng.guns.rabbitmq.service.impl;

import cn.stylefeng.guns.rabbitmq.common.ProductDoulData;
import cn.stylefeng.guns.rabbitmq.model.ResultParam;
import cn.stylefeng.guns.rabbitmq.service.ICardService;
import cn.stylefeng.guns.rabbitmq.util.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service("doulCardMoreService")
@Slf4j
public class DoulCardMoreServiceImpl implements ICardService {
    private static final String account = "18771118457";
    private static final String signKey = "ffd4511ae9f34e77b7f6d043cab58eaf";
    private static final String paramKey = "6Gt5J8nY";
    private static final String callBackUrl = "http://47.96.236.71:30116/rabbitmq/card/notify-form/doulCardMoreService";

    @Value("${order.approveUrl}")
    private String approveUrl;

    /**
     * 发送
     *
     * @param object
     */
    @Override
    public boolean sendCardSubmit(JSONObject object) {
        log.info("豆乐销卡more接收到数据：" + object.toJSONString() + "，开始提交数据到豆乐销卡more");
        JSONObject order = object.getJSONObject("order");
        JSONObject orderItem = object.getJSONObject("orderItem");
        JSONObject channel = object.getJSONObject("channel");
        JSONArray channelParam = channel.getJSONArray("params");
        String httpUrl = channel.getString("apiUrl");
        Map<String, String> cparam = new HashMap<>();
        //先拆分固定参数
        for (Object objParam : channelParam) {
            JSONObject jsonObject = (JSONObject)objParam;
            if (!StringUtils.isEmpty(jsonObject.getString("value"))) {
                cparam.put(jsonObject.getString("key"), jsonObject.getString("value"));
            }
        }
        String productKey =  cparam.get("productKey");
        try {
            String quota = order.getString("quota");
            Map<String, String> param = new HashMap<>();
            if (!StringUtils.isEmpty(orderItem.getString("cardNo"))) {
                param.put("card_no", orderItem.getString("cardNo"));
            } else {
                param.put("card_no", "");
            }
            param.put("app_id", account);
            param.put("timestamp", System.currentTimeMillis() + "");
            param.put("order_no", order.getString("orderNo"));
            param.put("notify_url", callBackUrl);
            if (ProductDoulData.productMap.get(productKey) != null) {
                param.put("product_no", ProductDoulData.productMap.get(productKey).get(quota));
            } else {
                log.error("豆乐卡该产品未设置");
                return false;
            }
            param.put("card_password", EncryptionUtil.Encode( paramKey, orderItem.getString("cardPassword")));
            param.put("effective_time", DateUtil.getDate(DateUtil.addMonth(new Date(), 2)));
            SortedMap<String, String> param2 = new TreeMap<>();
            param2.putAll(param);
            String sign = EncryptionUtil.encodeSign(param2, signKey);
            param.put("sign", sign);
            log.info("向豆乐销卡more提交数据：" + JSONObject.toJSONString(param));
            String resultStr = HttpUtil.sendPost(httpUrl, param, "utf-8");
            log.info("豆乐销卡more返回：" + resultStr);
            if (!StringUtils.isEmpty(resultStr)) {
                JSONObject result = JSONObject.parseObject(resultStr);
                if (result.getString("code").equals("7000")) {
                    return true;
                } else {
                    JSONObject body = new JSONObject();
                    body.put("apiSign", "pmy2019app");
                    body.put("approveStatus", false);
                    body.put("orderNo", order.getString("orderNo"));
                    body.put("itemQuota", null);
                    body.put("payAmount", null);
                    body.put("adminApprove", false);
                    body.put("remark", "核销失败");
                    String resultA = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                    JSONObject resJson = JSONObject.parseObject(resultA);
                    if (resJson.getBoolean("success") || resJson.getIntValue("code") == 505) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            log.error("豆乐销卡moremd5错误");
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 销卡回调处理
     *
     * @param param
     */
    @Override
    public boolean cardNotify(ResultParam param) {
        String app_id = param.getApp_id();
        String timestamp = param.getTimestamp();
        String state = param.getState();
        String order_no = param.getOrder_no();
        String price = param.getPrice();
        String sign = param.getSign();
        SortedMap<String, String> param2 = new TreeMap<>();
        param2.put("app_id", app_id);
        param2.put("timestamp", timestamp);
        param2.put("state", state);
        param2.put("order_no", order_no);
        param2.put("price", price);
        String signStr = EncryptionUtil.encodeSign(param2, signKey);
        log.info("豆乐销卡more回调：" + signStr);
        try {
            if (signStr.equals(sign)) {
                if (state.equals("SUCCESS") ) {//成功
                    JSONObject body = new JSONObject();
                    body.put("apiSign", "pmy2019app");
                    body.put("approveStatus", true);
                    body.put("orderNo", order_no);
                    body.put("costAmount", price);
                    body.put("remark", "成功");
                    body.put("adminApprove", false);
                    String result = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                    JSONObject resJson = JSONObject.parseObject(result);
                    if (resJson.getBoolean("success")) {
                        return true;
                    }
                } else if (state.equals("FAIL")) {//失败
                    JSONObject body = new JSONObject();
                    body.put("apiSign", "pmy2019app");
                    body.put("approveStatus", false);
                    body.put("orderNo", order_no);
                    //body.put("itemQuota", realPrice);
                    //body.put("payAmount", actualAmount);
                    body.put("remark", "失败");
                    body.put("adminApprove", false);
                    String result = HttpUtil.sendPostJson(approveUrl, body.toJSONString(), "utf-8");
                    JSONObject resJson = JSONObject.parseObject(result);
                    if (resJson.getBoolean("success")) {
                        return true;
                    }
                }
            } else {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @return
     */
    @Override
    public Object returnOk() {
        return "ok";
    }


    public static void main(String[] args) {

        try {
            Map<String, String> param = new HashMap<>();
            param.put("app_id", account);
            param.put("timestamp", System.currentTimeMillis() + "");

            param.put("order_no", "LX201909181756195593973104");
            param.put("notify_url", "www.baidu.com");
            //param.put("cardPwd", "2121212121212");
            //param.put("dateTime", DateUtil.DateToString(new Date(), DateStyle.YYYYMMDDHHMMSS));
            String retUrl = param.get("retUrl");
            param.put("product_no", "12001004");
            param.put("card_no", "");
            param.put("card_password", EncryptionUtil.Encode( "6Gt5J8nY", "13A9-FDD5-40F2-43BA"));
            param.put("effective_time", DateUtil.getDate(DateUtil.addMonth(new Date(), 2)));
            SortedMap<String, String> param1 = new TreeMap<>();
            param1.putAll(param);
            String sign = EncryptionUtil.encodeSign(param1, signKey);
            param.put("sign", sign);
            String resultStr = HttpUtil.sendPost("http://api.douleka.com:11140/collect/cards", param, "utf-8");
            System.out.println(resultStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
